package com.bitbank.smartdevice.adapter.base

import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.view.View
import android.view.ViewGroup


/**
 *  Date：2018/12/10
 *  Author：xulee
 *  Desc：
 */
class EmptyWrapper<T> (val mInnerAdapter: RecyclerView.Adapter<MViewHolder>) :
    RecyclerView.Adapter<MViewHolder>() {
    private lateinit var mEmptyView: View
    private var mEmptyLayoutId: Int = 0

    private val isEmpty: Boolean
        get() = (mEmptyLayoutId != 0) && mInnerAdapter.itemCount == 0

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MViewHolder {
        if (isEmpty) {
            val holder: MViewHolder
            holder = MViewHolder.createViewHolder(parent.context, parent, mEmptyLayoutId)
            return holder
        }
        return mInnerAdapter.onCreateViewHolder(parent, viewType)
    }

    override fun onAttachedToRecyclerView(recyclerView: RecyclerView) {
        WrapperUtils.onAttachedToRecyclerView(mInnerAdapter, recyclerView, object : WrapperUtils.SpanSizeCallback {
            override fun getSpanSize(
                layoutManager: GridLayoutManager,
                oldLookup: GridLayoutManager.SpanSizeLookup,
                position: Int
            ): Int {
                return if (isEmpty) {
                    layoutManager.spanCount
                } else oldLookup.getSpanSize(position)
            }
        })


    }

    override fun onViewAttachedToWindow(holder: MViewHolder) {
        mInnerAdapter.onViewAttachedToWindow(holder)
        if (isEmpty) {
            WrapperUtils.setFullSpan(holder)
        }
    }


    override fun getItemViewType(position: Int): Int {
        return if (isEmpty) {
            ITEM_TYPE_EMPTY
        } else mInnerAdapter.getItemViewType(position)
    }

    override fun onBindViewHolder(holder: MViewHolder, position: Int) {
        if (isEmpty) {
            return
        }
        mInnerAdapter.onBindViewHolder(holder, position)
    }

    override fun getItemCount(): Int {
        return if (isEmpty) 1 else mInnerAdapter.itemCount
    }


    fun setEmptyView(emptyView: View) {
        mEmptyView = emptyView
    }

    fun setEmptyView(layoutId: Int) {
        mEmptyLayoutId = layoutId
    }

    companion object {
        val ITEM_TYPE_EMPTY = Integer.MAX_VALUE - 1
    }

}